<template>
  <div class="employee-contracts-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>待签订合同</h2>
        <!-- 返回上一级按钮（美化） -->
        <button @click="goBack" class="btn btn-back">
          <i class="fa fa-arrow-left mr-2"></i>返回上一级
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 合同列表 -->
    <div v-if="!loading && contracts.length > 0" class="card mt-4">
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table w-full border-collapse" style="table-layout: fixed;">
            <thead class="bg-light">
            <tr>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同ID</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同名称</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">项目经理</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">状态</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">创建时间</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in contracts" :key="contract.id" class="border-b border-gray-200 hover:bg-gray-50 transition-colors duration-200">
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.id }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.name }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.projectManager?.name || '未指定' }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">
                <!-- 状态标签化显示 -->
                <span :class="`status-tag status-${contract.status.toLowerCase()}`">
                  {{ formatStatus(contract.status) }}
                </span>
              </td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ formatDate(contract.createTime) }}</td>
              <td class="py-3 px-4 border-b border-gray-200">
                <!-- 查看详情按钮（美化） -->
                <button @click="viewContract(contract.id)" class="btn btn-view me-2">
                  <i class="fa fa-eye mr-2"></i>查看详情
                </button>
                <!-- 确认合同按钮（美化） -->
                <button @click="signContract(contract.id)" class="btn btn-sign">
                  <i class="fa fa-file-signature mr-2"></i>确认合同
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件（按钮美化） -->
        <div class="pagination mt-3 d-flex justify-content-between">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalItems }} 条
          </div>
          <div class="pagination-buttons">
            <button
                @click="prevPage"
                :disabled="currentPage === 0"
                class="btn btn-page"
            >
              <i class="fa fa-chevron-left"></i> 上一页
            </button>
            <span class="page-info mx-2">
              第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
            </span>
            <button
                @click="nextPage"
                :disabled="currentPage === totalPages - 1"
                class="btn btn-page"
            >
              下一页 <i class="fa fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 无合同提示 -->
    <div v-else-if="!loading && contracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-file-contract text-muted display-4 mb-3"></i>
          <h4>暂无待签订合同</h4>
          <p class="text-muted">没有需要您签订的合同记录</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'EmployeePendingSignContracts',
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(true)
    const errorMessage = ref('')
    const contracts = ref([])
    const currentPage = ref(0)
    const pageSize = ref(10)
    const totalPages = ref(1)
    const totalItems = ref(0)

    // 用户信息
    const employeeId = ref(null)
    const employeePosition = ref('')

    // 状态映射表
    const statusMap = {
      "DRAFT": "草稿",
      "PENDING_REVIEW": "待审核",
      "PENDING_FINANCE_AUDIT": "待财务审核",
      "PENDING_CONFIRMATION": "待签订",
      "CONFIRMED": "已签订",
      "REVIEW_FAILED": "审核失败",
      "COMPLETED": "已完成"
    }

    // 配置请求头
    const setupRequestHeaders = () => {
      if (store.state.user) {
        axios.defaults.headers.common['X-Employee-Id'] = store.state.user.id
        axios.defaults.headers.common['X-Employee-Position'] = store.state.user.position
      }
    }

    // 返回上一级
    const goBack = () => {
      router.go(-1)
    }

    // 获取待签订合同数据
    const fetchPendingSignContracts = () => {
      loading.value = true
      errorMessage.value = ''

      if (!employeeId.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/pending-sign/${employeeId.value}`, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          page: currentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            contracts.value = response.data || []
            totalItems.value = response.data.length
            totalPages.value = Math.ceil(totalItems.value / pageSize.value)
          })
          .catch(error => {
            console.error('获取待签订合同失败', error)
            if (error.response) {
              if (error.response.status === 403) {
                errorMessage.value = '权限不足，无法查看待签订合同'
              } else if (error.response.status === 400) {
                errorMessage.value = '请求参数错误，请检查分页参数'
              } else {
                errorMessage.value = error.response.data?.message || '获取合同失败，请稍后再试'
              }
            } else {
              errorMessage.value = '网络错误，请检查连接'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 查看合同详情
    const viewContract = (contractId) => {
      router.push(`/contracts/${contractId}/detail2`)
    }

    // 确认签订合同
    const signContract = (contractId) => {
      router.push(`/contracts/${contractId}/sign`)
    }

    // 分页操作
    const prevPage = () => {
      if (currentPage.value > 0) {
        currentPage.value--
        fetchPendingSignContracts()
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
        fetchPendingSignContracts()
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 格式化状态
    const formatStatus = (statusCode) => {
      return statusMap[statusCode] || statusCode
    }

    onMounted(() => {
      if (store.state.user) {
        employeeId.value = store.state.user.id
        employeePosition.value = store.state.user.position
        setupRequestHeaders()
      }

      watch([
        () => store.state.user?.id,
        () => store.state.user?.position
      ], () => {
        if (store.state.user) {
          employeeId.value = store.state.user.id
          employeePosition.value = store.state.user.position
          setupRequestHeaders()
          fetchPendingSignContracts()
        }
      })

      fetchPendingSignContracts()
    })

    return {
      loading,
      errorMessage,
      contracts,
      currentPage,
      pageSize,
      totalPages,
      totalItems,
      goBack,
      viewContract,
      signContract,
      prevPage,
      nextPage,
      formatDate,
      formatStatus
    }
  }
}
</script>

<style scoped>
.employee-contracts-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 基础按钮样式 */
.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn i {
  font-size: 14px;
}

/* 按钮交互反馈 */
.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 按钮分类样式 */
.btn-back {
  background-color: #6c757d;
  color: #fff;
}

.btn-back:hover {
  background-color: #5a6268;
}

.btn-view {
  background-color: #007bff;
  color: #fff;
}

.btn-view:hover {
  background-color: #0069d9;
}

.btn-sign {
  background-color: #28a745;
  color: #fff;
}

.btn-sign:hover {
  background-color: #218838;
}

.btn-page {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #dee2e6;
  padding: 4px 10px;
}

.btn-page:hover {
  background-color: #e9ecef;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 错误消息 */
.error-message {
  color: #dc3545;
  background-color: #f8d7da;
  padding: 12px 15px;
  border-radius: 4px;
  margin: 20px 0;
  display: flex;
  align-items: center;
  border-left: 3px solid #dc3545;
}

/* 卡片样式 */
.card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.card-body {
  padding: 20px;
}

/* 表格样式 */
.table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}

.table th,
.table td {
  padding: 12px 15px;
  vertical-align: middle;
  text-align: left;
  word-break: break-word;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #e9ecef;
}

.table tr:hover {
  background-color: #f8fafc;
}

.table td {
  border-top: 1px solid #e9ecef;
}

/* 状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: 500;
}

/* 状态颜色区分 */
.status-draft {
  background-color: #e9ecef;
  color: #495057;
}

.status-pending_review {
  background-color: #fff3cd;
  color: #856404;
}

.status-pending_finance_audit {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-pending_confirmation {
  background-color: #d6eaf8;
  color: #1b6ec2;
}

.status-confirmed {
  background-color: #d4edda;
  color: #155724;
}

.status-review_failed {
  background-color: #f8d7da;
  color: #721c24;
}

.status-completed {
  background-color: #c3e6cb;
  color: #155724;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.pagination-buttons {
  display: flex;
  align-items: center;
}

.page-info {
  color: #495057;
  font-size: 14px;
}

/* 空状态样式 */
.empty-message {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8fafc;
  border-radius: 6px;
  border: 1px dashed #e2e8f0;
}

.empty-message i {
  color: #94a3b8;
  margin-bottom: 15px;
}

.empty-message h4 {
  color: #1e293b;
  margin-bottom: 8px;
}

.empty-message p {
  color: #64748b;
  margin: 0;
}
</style>